package com.henry.controller;

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.cloud.nacos.NacosServiceManager;
import com.alibaba.nacos.api.annotation.NacosInjected;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.henry.pojo.Stu;
import com.henry.service.StuService;
import com.henry.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @program: old-service-call
 * @description:
 * @author: Henry.zhang
 * @create: 2022-08-15 11:24
 */
@RestController
@RequestMapping("stu")
public class StudentController {
    /*
    属性列表
    */
    @Autowired
    private StuService stuService;

    @Autowired
    private NacosServiceManager nacosServiceManager;
    @Autowired
    private NacosDiscoveryProperties nacosDiscoveryProperties;

//    @Autowired
//    @NacosInjected
//    private NamingService namingService;

    /**
     * 获取注册中心某服务的所有实例信息
     * @param serviceName
     * @return
     * @throws NacosException
     */
    @RequestMapping(value = "/get", method = RequestMethod.GET)
    @ResponseBody
    public List<Instance> get(@RequestParam String serviceName) throws NacosException {
        NamingService namingService = nacosServiceManager.getNamingService(nacosDiscoveryProperties.getNacosProperties());
        return namingService.getAllInstances(serviceName);
    }

    @Value("${server.port}")
    private String port;

    @GetMapping("foo")
    public R foo(@RequestParam("number") Integer number) throws Exception{
        if(number % 2 != 0){
            throw new Exception("出错了~");
        }
        return new R(100,"ok",number.toString());
    }

    @GetMapping("getAll")
    public R getAll(){
        List<Stu> list = stuService.list();

//        try {
//            Thread.sleep(8000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }

        return new R(200,port,list);
    }

    @GetMapping("getOne")
    public R getOne(Integer stuId){
        QueryWrapper<Stu> wrapper = new QueryWrapper();
        wrapper.eq("id",stuId);
        Stu stu = stuService.getOne(wrapper);

        return R.ok(stu);
    }

    @GetMapping("test")
    public R test(@RequestParam("stuId") Integer stuId) throws Exception {
        if(stuId < 0){
            throw new Exception();
        }

        return R.ok(stuId);
    }

}
